﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMK.PaketTracker.Server.Definitions;
using System.Data.SqlClient;
using System.Data;

namespace MMK.PaketTracker.Server.Database
{
    public class AdressenSqlDataLayer : BaseSqlDataLayer
    {
        public AdressenSqlDataLayer(string DbConnectionString) 
        { 
            this.Initialize(DbConnectionString); 
        }
        
        public void CreateNewAdresse(string paketIdent, Adresse adresse, AdresseType type)
        {
            string sql = "INSERT INTO [Adressen] VALUES(@ID, @Type, @PaketIdent, @Vorname, @Name, @Strasse, @Hausnummer, " +
                "@PLZ, @ORT)";

            //this.Initialize(Config.DbConnectionString);
            
            this.ExecuteNonQuery(sql,
                new SqlParameter("@ID", adresse.Guid),
                new SqlParameter("@Type", type),
                new SqlParameter("@PaketIdent", paketIdent),
                new SqlParameter("@Vorname", adresse.Vorname),
                new SqlParameter("@Name", adresse.Name),
                new SqlParameter("@Strasse", adresse.Strasse),
                new SqlParameter("@Hausnummer", adresse.Hausnummer),
                new SqlParameter("@PLZ", adresse.PLZ),
                new SqlParameter("@Ort", adresse.Ort));
        }

        public Adresse LoadAdresse(Guid id)
        {
            string sql = "SELECT * FROM [Adressen] WHERE ID=@ID";

            //this.Initialize(Config.DbConnectionString);
            
            using (IDataReader reader = this.GetDataReader(sql, new SqlParameter("@ID", id)))
            {
                return (reader.Read() ? LoadAdresseFromDataReader(reader) : null);
            }
        }

        public Adresse LoadAdresse(string paketIdent, AdresseType type)
        {
            string sql = "SELECT * FROM [Adressen] WHERE PaketIdent=@PaketIdent AND Type=@Type";

            using (IDataReader reader = this.GetDataReader(sql,
                new SqlParameter("@PaketIdent", paketIdent),
                new SqlParameter("@Type", type)))
            {
                return (reader.Read() ? LoadAdresseFromDataReader(reader) : null);
            }
        }

        public Adresse LoadAdresseFromDataReader(IDataReader reader)
        {
            Adresse adresse = new Adresse(this.GetGuid(reader, "ID"));
            adresse.Vorname = this.GetString(reader, "Vorname");
            adresse.Name = this.GetString(reader, "Name");
            adresse.Strasse = this.GetString(reader, "Strasse");
            adresse.Hausnummer = this.GetString(reader, "Hausnummer");
            adresse.PLZ = this.GetString(reader, "PLZ");
            adresse.Ort = this.GetString(reader, "Ort");

            return adresse;

        }
    }
}
